import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  message,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';

import SelectModalElem from './components/SelectModal';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;

interface BoxManageAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  bluetooth: string[];
  firmware: string[];
  postTariffList: any[];
  INITINFO: any;
  location: { query: any };
}

interface BoxManageAddState {
  modalVisible: boolean;
  postInfo: { id?: number; name?: string };
  gardenInfo: { id?: number; name?: string };
  posthouseId: number;
  type: number;
  selectType: number;
  is_detail: boolean;
}

@connect(
  ({
    boxManagementAdd: {
      detailInfo, bluetooth, firmware, postTariffList,
    },
    common: { INITINFO },
  }: any) => ({
    detailInfo,
    bluetooth,
    firmware,
    postTariffList,
    INITINFO,
  }),
)
class BoxManagementAddElem extends Component<BoxManageAddProps, BoxManageAddState> {
  state: BoxManageAddState = {
    modalVisible: false,
    postInfo: {},
    gardenInfo: {},
    posthouseId: 0,
    type: 1,
    selectType: 1,
    is_detail: false,
  };

  static getDerivedStateFromProps(nextProps: BoxManageAddProps, perState: BoxManageAddState) {
    const { detailInfo } = nextProps;
    const { is_detail } = perState;
    if (detailInfo.id && !is_detail) {
      return {
        postInfo: { id: detailInfo.posthouseId, name: detailInfo.posthouseName },
        gardenInfo: { id: detailInfo.gardenId, name: detailInfo.gardenName },
        type: detailInfo.type,
        selectType: detailInfo.type,
        is_detail: true,
      };
    }
    return null;
  }

  componentDidMount() {
    const { type } = this.state;
    const { location: { query: { id } } } = this.props;
    if (id) this.fetchDetailInfo(id);

    this.fetchAction('fetchEdition', { type });
    this.fetchAction('fetchPosthouseTariff');
    this.fetchAction('common/fetchPassword');
  }

  componentDidUpdate(props: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && id !== props.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'boxManagementAdd/fetch',
      payload: { id },
    });
  };

  handleSelectType = (type: number) => {
    this.setState({ type });
    this.fetchAction('fetchEdition', { type });
  };

  handleChangeModal = (modalVisible: boolean, selectType: number, postOrGarden: any = {}) => {
    const { postInfo, gardenInfo, posthouseId } = this.state;
    this.setState(
      {
        selectType,
        modalVisible,
        postInfo: postOrGarden.id && selectType === 1 ? postOrGarden : postInfo,
        gardenInfo: postOrGarden.id && selectType === 2 ? postOrGarden : gardenInfo,
        posthouseId: postOrGarden.id || posthouseId,
      },
      () => {
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue({
          posthouseId: postOrGarden.name || postInfo.name,
          gardenId: postOrGarden.name || gardenInfo.name,
        });
      },
    );
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { longitude, latitude } = values;
      if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
        message.error('经度输入不正确');
        return;
      }
      if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
        message.error('纬度输入不正确');
        return;
      }

      const { type } = this.state;
      const code = type === 1 ? 'X' : 'H';
      if (values.code.indexOf(code) < 0) {
        message.error(`箱体编号${code}为必填字段`);
        return;
      }

      const {
        postInfo: { id: posthouseId = '' },
        gardenInfo: { id: gardenId = '' },
      } = this.state;
      const params = { ...values, posthouseId, gardenId };

      const { location: { query } } = this.props;
      if (query) params.id = query.id;
      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `boxManagementAdd/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      modalVisible, postInfo, gardenInfo, type, selectType,
    } = this.state;
    const {
      form: { getFieldDecorator },
      detailInfo,
      bluetooth,
      firmware,
      postTariffList,
      INITINFO: { passwordType },
    } = this.props;

    const postProps = {
      modalVisible,
      selectType,
      changeModal: this.handleChangeModal.bind(this),
      fetchAction: this.fetchAction.bind(this),
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} title="编辑宝箱/宝盒信息">
          <Form hideRequiredMark className="tableListForm">
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　箱体编号" colon={false}>
                  {getFieldDecorator('code', {
                    initialValue: detailInfo.code || (type === 1 ? 'X' : 'H'),
                    rules: [{ required: true, message: '请输入箱体编号' }],
                  })(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　蓝牙名称" colon={false}>
                  {getFieldDecorator('bluetoothName', {
                    initialValue: detailInfo.bluetoothName,
                    rules: [{ required: true, message: '请输入蓝牙名称' }],
                  })(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: detailInfo.status || 1,
                    rules: [{ required: true, message: '请选择状态' }],
                  })(
                    <Select placeholder="请选择">
                      <Option value={1}>调试中</Option>
                      <Option value={2}>运营中</Option>
                      <Option value={3}>已删除</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　箱体名称" colon={false}>
                  {getFieldDecorator('name', {
                    initialValue: detailInfo.name,
                    rules: [{ required: true, message: '请输入箱体名称' }],
                  })(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　蓝牙锁版本" colon={false}>
                  {getFieldDecorator('btLockVersion', {
                    initialValue: detailInfo.btLockVersion || bluetooth[0],
                    rules: [{ required: true, message: '请选择蓝牙锁版本' }],
                  })(
                    <Select placeholder="请选择">
                      {bluetooth.map((item: string) => (
                        <Option value={item} key={item}>{item}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　经度" colon={false}>
                  {getFieldDecorator('longitude', {
                    initialValue: detailInfo.longitude || 0,
                    rules: [{ required: true, message: '请输入经度' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      step={0.00000000000001}
                      placeholder="请输入"
                    />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　箱体类型" colon={false}>
                  {getFieldDecorator('type', {
                    initialValue: type,
                    rules: [{ required: true, message: '请选择箱体类型' }],
                  })(
                    <Select placeholder="请选择" onChange={this.handleSelectType}>
                      <Option value={1}>宝箱</Option>
                      <Option value={2}>宝盒</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　短信地址" colon={false}>
                  {getFieldDecorator('addr', {
                    initialValue: detailInfo.addr,
                    rules: [{ required: true, message: '请输入短信地址' }],
                  })(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　纬度" colon={false}>
                  {getFieldDecorator('latitude', {
                    initialValue: detailInfo.latitude || 0,
                    rules: [{ required: true, message: '请输入纬度' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      step={0.00000000000001}
                      placeholder="请输入"
                    />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　结构版本" colon={false}>
                  {getFieldDecorator('structVersion', {
                    initialValue: detailInfo.structVersion || firmware[0],
                    rules: [{ required: true, message: '请选择结构版本' }],
                  })(
                    <Select placeholder="请选择">
                      {firmware.map((item: string) => (
                        <Option value={item} key={item}>{item}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                {type === 1 && (
                  <Item label="　　　　驿站" colon={false}>
                    {getFieldDecorator('posthouseId', {
                      initialValue: postInfo.name,
                      rules: [{ required: true, message: '请选择驿站' }],
                    })(
                      <Input
                        allowClear
                        readOnly
                        placeholder="请选择"
                        suffix={<SearchOutlined style={{ color: '#ccc', fontSize: 20 }} />}
                        onClick={() => this.handleChangeModal(true, 1)}
                      />,
                    )}
                  </Item>
                )}
                {type === 2 && (
                  <Item label="　　　　小区" colon={false}>
                    {getFieldDecorator('gardenId', {
                      initialValue: gardenInfo.name,
                      rules: [{ required: false, message: '请选择小区' }],
                    })(
                      <Input
                        allowClear
                        readOnly
                        placeholder="请选择"
                        suffix={<SearchOutlined />}
                        onClick={() => this.handleChangeModal(true, 2)}
                      />,
                    )}
                  </Item>
                )}
              </Col>
              <Col md={8} sm={24}>
                {type === 1 && (
                  <Item label="　　　　套餐" colon={false}>
                    {getFieldDecorator('tariffpkgId', {
                      initialValue: detailInfo.tariffpkgId || 0,
                      rules: [{ required: true, message: '请选择套餐' }],
                    })(
                      <Select
                        showSearch
                        placeholder="请选择"
                        filterOption={(input: any, option: any) => (
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        )}
                      >
                        <Option value={0}>无</Option>
                        {postTariffList.map((item: any) => (
                          <Option value={item.id} key={item.id}>{item.name}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                )}
                {type === 2 && (
                  <Item label="宝盒专属用户" colon={false}>
                    {getFieldDecorator('managerName', {
                      initialValue: detailInfo.managerName,
                      rules: [{ required: false, message: '请输入宝盒专属用户' }],
                    })(
                      <Input allowClear placeholder="请输入" />,
                    )}
                  </Item>
                )}
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              {type === 1 && (
                <Col md={8} sm={24}>
                  <Item label="　　密码类型" colon={false}>
                    {getFieldDecorator('openCodeType', {
                      initialValue: detailInfo.openCodeType || 0,
                      rules: [{ required: true, message: '请选择密码类型' }],
                    })(
                      <Select placeholder="请选择">
                        <Option value={0}>无</Option>
                        {passwordType.map((item: any) => (
                          <Option value={item.value} key={item.value}>{item.label}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
              )}
              {type === 2 && (
                <Col md={8} sm={24}>
                  <Item label="　　　手机号" colon={false}>
                    {getFieldDecorator('managerPhone', {
                      initialValue: detailInfo.managerPhone,
                      rules: [{ required: true, message: '请输入收件人手机号' }],
                    })(
                      <Input allowClear type="number" placeholder="请输入" />,
                    )}
                  </Item>
                </Col>
              )}
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Button
                  type="primary"
                  onClick={this.handleSubmit}
                >
                  保存
                </Button>
                <Button
                  ghost
                  type="primary"
                  className="marginL16"
                  onClick={() => router.goBack()}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>
        <SelectModalElem {...postProps} />
      </Fragment>
    );
  }
}

export default Form.create<BoxManageAddProps>()(BoxManagementAddElem);
